<?php

namespace App\Http\Controllers\Backend;

use App\Repository\Models\Action;
use App\Repository\Models\ActionPermission;
use App\Repository\Models\Menu;
use App\Repository\Models\MenuPermission;
use App\Repository\Models\Permission;
use App\Repository\Models\PermissionRole;
use App\Repository\Repositories\Interfaces\RoleRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 角色管理控制器
 *
 * @package App\Http\Controllers\Backend
 */
class RoleController extends BaseController
{
    private $roleRepository;

    public function __construct(RoleRepository $roleRepository)
    {
        parent::__construct();
        $this->roleRepository = $roleRepository;
    }
    /**
     * 角色列表
     *
     * @return \Illuminate\Http\Response1
     */
    public function index()
    {
        $ret = $this->roleRepository->orderBy('id','desc')->paginate($this->perPage);
        $data = ['list' => $ret['data'],'page' => $ret['meta']['pagination']];
        return $this->success('ok',$data);
    }

    /**
     * 增加角色
     *
     * @param  \App\Http\Requests\Form\RoleCreateForm $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,[
            'name'         => 'required',
            'display_name' => 'required',
            'description'  => 'required',
        ],[
            'name.required'         => '角色标识不能为空',
            'display_name.required' => '角色名称不能为空',
            'description.required'  => '角色描述不能为空',
        ]);
        try {
            if ($role = $this->roleRepository->create($request->only(['name','display_name','description']))) {

                $data=$request->all();

                //添加菜单权限
                $Menu = Menu::query()->with(['menuPermission'])->whereIn('id',$data['menu'])->orderBy('id','desc')->get()->toArray();
                foreach($Menu as $k =>$v){
                    if(!empty($v['menu_permission'])){
                        $roledata=[
                            'permission_id'=>$v['menu_permission']['permission_id'],
                            'role_id'=>$role['data']['role_id']
                        ];
                        PermissionRole::query()->create($roledata);
                    }
                }

                //添加操作权限
                $Action = Action::query()->with(['actionPermission'])->whereIn('id',$data['action'])->orderBy('id','desc')->get()->toArray();
                foreach($Action as $k =>$v){
                    if(!empty($v['action_permission'])){
                        $roledata=[
                            'permission_id'=>$v['action_permission']['permission_id'],
                            'role_id'=>$role['data']['role_id']
                        ];
                        PermissionRole::query()->create($roledata);
                    }
                }

                return $this->success('创建角色成功',$role['data']);
            }
        }
        catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     *  角色详情
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $ret = $this->roleRepository->find($id);
        return $this->success('ok', $ret['data']);
    }


    /**
     * 修改角色
     * @param  int                                    $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request,$id)
    {
        $this->validate($request,[
            'name'         => 'required',
            'display_name' => 'required',
            'description'  => 'required',
        ],[
            'name.required'         => '角色标识不能为空',
            'display_name.required' => '角色名称不能为空',
            'description.required'  => '角色描述不能为空',
        ]);
        DB::beginTransaction();
        try {
            if ($role = $this->roleRepository->update($request->all(['name','display_name','description']),$id)) {
                $data=$request->all();

                //如果权限有修改

//                if($data['menu']!=$data['old_permission']['menu'] || $data['action']!=$data['old_permission']['action']){
                    PermissionRole::query()->where("role_id",$id)->delete();
                    //添加菜单权限
                    $Menu = Menu::query()->with(['menuPermission'])->whereIn('id',$data['menu'])->orderBy('id','desc')->get()->toArray();
                    foreach($Menu as $k =>$v){
                        if(!empty($v['menu_permission'])){
                            $roledata=[
                                'permission_id'=>$v['menu_permission']['permission_id'],
                                'role_id'=>$id
                            ];
                            PermissionRole::query()->create($roledata);
                        }
                    }

                    //添加操作权限
                    $Action = Action::query()->with(['actionPermission'])->whereIn('id',$data['action'])->orderBy('id','desc')->get()->toArray();
                    foreach($Action as $k =>$v){
                        if(!empty($v['action_permission'])){
                            $roledata=[
                                'permission_id'=>$v['action_permission']['permission_id'],
                                'role_id'=>$id
                            ];
                            PermissionRole::query()->create($roledata);
                        }

                    }
//                }

                DB::commit();
                return $this->success("编辑角色成功",$Menu);
            }
        }
        catch (\Exception $e) {
            DB::rollback(); //事务回滚;
            return $this->error($e->getMessage());
        }
    }

    /**
     * 删除角色
     *
     * @param  int $id
     *gg
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        try {
            if ($this->roleRepository->delete($id)) {
                return $this->success("删除角色成功");
            }
        }
        catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 根据角色获取权限
     *
     * @param int $id
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function permission($id)
    {
        $role = $this->roleRepository->skipPresenter(1)->find($id);
        $data = $this->roleRepository->getTypeGroupPermissionsByRoleModel($role);
        return $this->success('ok', ['permissions' => $data]);
    }


    /**
     * 角色赋权操作
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function associatePermission($id,Request $request)
    {
        $this->validate($request,[
           'permissions' => 'required|array' 
        ]);
        $permissions = $request->input('permissions',[]);
        try {
            $role = $this->roleRepository->skipPresenter(1)->find($id);
            if ($role->perms()->sync($permissions)) {
                return $this->success('角色赋权成功');
            } else {
                return $this->error('角色赋权失败');
            }
        }
        catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 根据角色获取权限
     *
     * @param int $id
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function permission_role($id)
    {

        $role = $this->roleRepository->with('permissionRole')->find($id);
        $permission=[];
        foreach($role['data']['permission_role'] as $k=>$v){
            $per=Permission::query()->where('id',$v['permission_id'])->get()->toArray();
            $permission[]=$per[0];
        }
        $menu=[];
        $action=[];
        foreach($permission as $k=>$v){
            if($v['type']=='menu'){
                $menu_arr=MenuPermission::query()->where('permission_id',$v['permission_id'])->get()->toArray();
                if (isset($menu_arr[0]))
                    $menu[]=$menu_arr[0]['menu_id'];
            }else{
                $act_arr=ActionPermission::query()->where("permission_id",$v['permission_id'])->get()->toArray();
                if($act_arr){
                    $action[]=$act_arr[0]['action_id'];
                }
            }
        }
        $data=[
            'menu'=>$menu,
            'action'=>$action,
        ];
        return $this->success('ok',  $data);
    }


}
